const redis = require( 'redis' );
const util = require( 'util' );
const redisWrapper = require('co-redis');
const config = require( '../config' );

const redisConf = config.redis;

let client;

const initClient = () => {

    const { port, host } = redisConf;

    let redisClient = redis.createClient( {
        host,
        port,
        retry_strategy: function() {
            return null;
        }
    } );

    client = redisWrapper( redisClient );

    redisClient.on( 'error', err => {
        return console.log( 'redis 创建连接失败' );
    } );

}

const del = async function ( key ) {

    if ( !client ) initClient();

    let result = null;

    try {

        result = await client.del( key );

    } catch( e ) {

        client = null;

        console.log( 'redis 删除失败' );

    }

    return result;

}

const get = async function ( key ) {

    if ( !client ) initClient();

    let result = null;

    try {

        result = await client.get( key );

    } catch( e ) {

        client = null;

        console.log( 'redis 查询失败' );

    }

    return result;

}

const set = async function ( key, value ) {

    if ( !client ) initClient();


    let result = null;

    try {

        result = await client.set( key, value );

    } catch( e ) {

        client = null;

        console.log( 'redis 设置失败' );

    }

    return result;

}

exports.del = del;
exports.get = get;
exports.set = set;
